package com.laicunba.event.listener;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.constant.TemplateConstant;
import com.laicunba.event.InviteEvent;
import com.laicunba.pojo.TemplateDO;
import com.laicunba.pojo.UserDO;
import com.laicunba.service.FinancingTargetService;
import com.laicunba.service.MobileMessageService;
import com.laicunba.service.RegistryService;
import com.laicunba.service.TemplateService;
import com.laicunba.service.UserService;
import com.laicunba.service.accounting.InviteRegistService;
import com.laicunba.util.StringUtil;

@Component
public class InviteListener implements ApplicationListener<InviteEvent> {
	@Autowired
	private RegistryService registryService;

	@Autowired
	private FinancingTargetService financingTargetService;
	@Autowired
	private InviteRegistService inviteRegistService;
	@Autowired
	private UserService userService;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private MobileMessageService mobileMessageService;

	@Override
	public void onApplicationEvent(InviteEvent event) {
		UserDO userDO = (UserDO) event.getSource();
		if (userDO == null || StringUtil.isEmpty(userDO.getInviteFrom())) {
			return;
		}
		Map<String, String> map = registryService.likeKey("act.invite.regist");
		if (map == null) {
			return;
		}

		String amount = map.get("act.invite.regist.amount");
		if (!"true".equalsIgnoreCase(map.get("act.invite.regist.open"))) {
			return;
		}
		if (StringUtil.isEmpty(amount) || !amount.matches("[0-9]+")) {
			return;
		}
		try {
			UserDO inviteCodeUserDO = userService.findByInviteCode(userDO.getInviteFrom());
			inviteRegistService.doAutoBuy(userDO, inviteCodeUserDO.getId(), BigDecimal.valueOf(Double.parseDouble(amount)));
			TemplateDO temp = templateService.findByCodeWidthDefault(TemplateConstant.MOBILE_MSG_INVITE_REGIST);
			Map param = new HashMap();
			param.put("buyAmount", amount);
			param.put("MobileShortNo", StringUtil.endSubstring(userDO.getMobile(), 4));
			String msg = templateService.simpleMerge(temp.getContent(), param);
			mobileMessageService.sendMsgAsync(inviteCodeUserDO.getMobile(), msg);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
